/***
 * @info 该文件来自windaeam。
 * 自定义标签模板
 * @time 2018/12/29
 */
(function($,window){
	if(!$ || !window){
		return ;
	}
	$.fn.cpTemple = function(isInit){

		var that = this ;
		var templeTable = null;
		var DEFAULT_TEMPLE_WIDTH = 575 ;
		var DEFAULT_TEMPLE_HEIGHT  = 500;
        var unit_value = 3.77 ; // px和毫米的转换关系

        var _DEFAULT_PADDING = 5;
        var _DEFAULT_LABEL_MARGIN = 3;
        var _DEFAULT_LABEL_PADDING = 0;
        
        var isInit = isInit ? true:false;
        
		/**
		 * 初始化页面数据
		 */
		this.initPageData = function(){
			$("#inputfile").fileUpload({
				callback:uploadSuccess
			});
		    var item = $(".design-area");
		    var width = item.outerWidth();
		    var height = item.outerHeight();
		    console.log("width:"+width+",height:"+height);
		    initFiledList();
			templeTable = initTempleTable();
		}
		
		/**
		 * 测试
		 */
		this.testTemple = function(id){
			loadHtml("customprint/toChooseTemple?id=" + id);
		}


		/**
		 * 修改模板
		 */
         this.editTemple = function (id){
			sys.getApiData("customprint/getTempleInfo",{id:id},function(data){
				console.log(data);
				that.setTempleInfo(data.temple);
				that.setLabelList(data.itemlist);
			},"GET");
		} 

         
     	//保存模板
 		this.saveTemple = function(){
 			var param = getTempleInfo();
 			if(!param.templename){
 				sys.topmsg("模板名称不能为空！");
 				return ;
 			}
 			param.itemJson = getItemDataList();
 			console.log(param);
 			sys.getApiData("customprint/saveTemple",param,function(data){
 				data.func = function(){
 					clearValue();
 					refalshTable();
 				}
 				sys.msg(data);
 			},"POST");
 		}
 		
 		
 		//新建
 		this.createTemple = function(){
 			clearValue();
			refalshTable();
 		}

 		//重置
 		this.resetTemple = function(){
 			if(getTempleId()!=0){
 				this.editTemple(getTempleId());
 			}else{
 				clearValue();
 			}
 		}

 		//删除
 		this.delEle = function(that){
 			$(that).parent().parent().remove();
 		}

 		//向上移动
 		this.upEle = function(that){
 		  if($(that).parent().parent().prev().length != 0){
 			  $(that).parent().parent().prev().before($(that).parent().parent());
 		  }
 		}

 		//向下移动
 		this.downEle = function(that){
 		  if($(that).parent().parent().next().length != 0){
 			  $(that).parent().parent().next().after($(that).parent().parent());
 		  }
 		}
		
 		

		/**
		 * 删除模板
		 */
		this.delTemple = function(id){
			stopPropagation();
			sys.confirm("确定删除该模板吗？", function(){
				sys.getApiData("customprint/delTemple", {id : id}, function(data){
					data.func = function(){
						refalshTable();
						if(getTempleId() == id){
							clearValue();
						}
					}
					sys.msg(data);
				}, "post");
			});
		} 
 		
		/**
		 * 获取模板列表
		 */
		function initTempleTable(){
			    var table = $(".dtable");
				var config = sys.defaultDatabeConfig("customprint/getTempleList", [ {
					data : null,
					render : function(data, type, full, meta){  
						return meta.row + 1 + meta.settings._iDisplayStart; }
				},
				{data: 'name'},
				{data: 'createtime'},
				{data: 'isenable',render:function(data){if(data==0){return "否"}else{return "<span style='color:#449F3F'>是</span>"}}},
				{data:null,render:function(data){
					return '<span class="btn btn-xs glyphicon glyphicon-trash" onclick="temple.delTemple('+data.id+')">删除</span>';
				   }
				}
				]);
				config.bSort=false;
				config.paging = false;
				table.dataTable(config);
				return table ;
		}

		/**
		 * 刷新列表
		 */
		function refalshTable(){
			templeTable.api().ajax.reload(null,false);
		} 


		/**
		 * 获取模板id
		 */
		function  getTempleId(){
			return $("#temple-id").val() || 0 ;
		} 

         
		/**
		 * 设置模板信息
		 */
		this.setTempleInfo = function (temple){
			$("#temple-id").val(temple.id);
			$("#temple-name").val(temple.name);
			$("#tem-width-attr").val(pXToHm(temple.width));
			$("#tem-width-px").html(temple.width);
			$("#tem-height-attr").val(pXToHm(temple.height));
			$("#tem-height-px").html(temple.height);
			$("#tem-isenable-attr").val(temple.isenable);
			
			var padding = temple.padding||_DEFAULT_PADDING; 
			
			$("#padding").val(padding);
			$(".design-area").outerWidth(temple.width).outerHeight(temple.height).css({"padding":padding+"px"});
			
		} 

		/**
		 * 设置标签集合
		 */
		this.setLabelList = function(itemlist){
			$(".design-area").empty();
			if(itemlist && itemlist.length>0){
				for(var key in itemlist){
					var v = itemlist[key];
					var at = $("#defalut-temple").html();
					at = at.replaceAll("%value",v.value)
					.replaceAll("%filed",v.filed)
					.replaceAll("%margin",v.margin)
					.replaceAll("%isvalue",v.isvalue)
					.replaceAll("%fontweight",v.fontweight)
					.replaceAll("%textalign",v.textalign)
					.replaceAll("%ishasurl",v.ishasurl)
					.replaceAll("%left",v.left||0)
					.replaceAll("%top",v.top||0);
					$(".design-area").append(at);
					that.setLabelStyle($(".design-area").find(".filed-div-item:last"),v);
					console.log(that.getTextAlign(v.textalign));
					____initResizeDrag(true);
				}
			}
		} 

		
		this.setLabelStyle = function(ele,v){
			ele.outerHeight(v.height)
			.outerWidth(v.width)
			.css({"line-height":v.height+"px",
				"font-size":v.fontsize+"px",
				"font-weight":this.getFontWeight(v.fontweight),
				"text-align":this.getTextAlign(v.textalign),
				"margin":(v.margin||_DEFAULT_LABEL_MARGIN)+"px",
				"padding-left":(v.padding||_DEFAULT_LABEL_PADDING)+"px",
				"left":(v.left||0)+"px",
				"top":(v.top||0)+"px",
				});
		}
		
		this.getFontWeight = function(fontweight){
			return fontweight == 1 ? "bold":"normal";
		}
		
		this.getTextAlign = function(textalign){
			return textalign ==0 ? "center":textalign == 1 ? "left":"right" ;
		}

		
		/**
		 * 获取标签项数据集合
		 */
		function getItemDataList(){
			var data = new Array();
			$(".design-area").find(".default-class").each(function(index,ele){
				
				var _t = $(this);
				
				var filed = _t.attr("data-filed");
				var value = _t.attr("data-value");
				var isvalue = _t.attr("data-isvalue");
				var textalign = _t.attr("data-textalign");
				var fontweight = _t.attr("data-fontweight");
				var ishasurl = _t.attr("data-ishasurl")||0;
				var width = _t.outerWidth();
				var height = _t.outerHeight();
				var fontsize = getFormatValue(_t.css('font-size'));
				var margin = getFormatValue(_t.css('margin'));
				var padding = getFormatValue(_t.css('padding-left'));
				var left = _t.css("left").replace("px","");
				var top = _t.css("top").replace("px","");
				data.push({
					filed:filed,
					value:value,
					orde:index,
					width:width,
					height:height,
					fontsize:fontsize,
					isvalue:isvalue,
					textalign:textalign,
					fontweight:fontweight,
					margin:margin,
					padding:padding,
					ishasurl:isNull(ishasurl),
					left:left,
					top:top,
				});
			})
			
			console.log(data);
			
			return  JSON.stringify(data);
		}


		/**
		 * 获取模板信息
		 */
		function getTempleInfo(){
			var templeid = $("#temple-id").val();
			var templename = $("#temple-name").val();
			var templewidth = $(".design-area").outerWidth()|| $("#tem-width-attr").val();
			var templeheight =$(".design-area").outerHeight()||  $("#tem-height-attr").val();
			var templeisenable =  $("#tem-isenable-attr").val();
			var padding = $("#padding").val();
			return {templeid:templeid,templename:templename,templewidth:templewidth,templeheight:templeheight,templeisenable:templeisenable,padding:padding};
		}
		
		
		
		function stopPropagation() {  
	        var e = window.event;  
	        if(e.stopPropagation) { //W3C阻止冒泡方法  
	            e.stopPropagation();  
	        } else {  
	            e.cancelBubble = true; //IE阻止冒泡方法  
	        }  
	    }
		
		function isNull(value){
			if(!value || value == 'null' || value === "undefind"){
				return "";
			}
			return value;
		}

		
		function isRightNumber(value){
			if(isNaN(value)){
		    	sys.topmsg("请填写数值!");
		 	   return false;
		    }
			return true;
		}
		
		/**
		 * 点击其他位置隐藏
		 */
		$(document).bind('click',function(){ 
			$(".filed-opration").hide();
		});


		//新增统一的change事件
		$('.select-change').bind('change', function() {
			
			var _id = $(this).attr("id");
			var _value = $(this).val();
			var _selectInput =  $(".filed-div-item.activi-edit-color");//选中的标签
			
			 switch (_id) {
				case "islabelname-attr"://是否显示前缀
					_selectInput.attr("data-isvalue",_value);
					break;
				case "textalign"://文字居中
					_selectInput.attr("data-textalign",_value);
					_selectInput.css({"text-align":that.getTextAlign(_value)});
					break;
				case "fontweight"://文字加粗
					_selectInput.attr("data-fontweight",_value);
					_selectInput.css({"font-weight":getFontWeight(_value)});
					break;
				case "ishasurl":
					_selectInput.attr("data-ishasurl",_value);
					break;
				default:
					break;
				}
			
		});
		
		
		
		
		//新增统一的input检测事件
		$(".input_change").bind("input propertychange",function(){
			
			var _id = $(this).attr("id");
			var _value = $(this).val();
			
			var _selectInput =  $(".filed-div-item.activi-edit-color");//选中的标签
			
			var _tempalte =  $(".design-area");//模板
			
			switch (_id) {
			
			case "padding"://模板padding
				
				 if(!isRightNumber(_value)) return ;
				 _tempalte.css({"padding":_value+"px"});
			    
				break;
				
			case "tem-height-attr"://模板高度
				
				if(!isRightNumber(_value)) return ;
				_value = hMToPx(_value);
			    if(_value > DEFAULT_TEMPLE_HEIGHT){
			    	sys.topmsg("标签纸最大高度不能超过130mm");
				 	return ;
			    }
			    $("#tem-height-px").html(_value);
			    _tempalte.css({"height":_value+"px"});
				
				break;
				
           case "tem-width-attr"://模板宽度
				if(!isRightNumber(_value)) return ;
				_value = hMToPx(_value);
			    if(_value > DEFAULT_TEMPLE_WIDTH){
			    	sys.topmsg("标签纸最大宽度不能超过152mm");
				 	return ;
			    }
			    $("#tem-width-px").html(_value);
			    $(".design-area").css({"width":_value+"px"});
			    break;
			    
           case "label-margin"://标签margin
			
				if(!isRightNumber(_value)) return ;
				_selectInput.css({"margin":_value+"px"});
				
				break; 
				
           case "label-padding"://标签padding
        	   
        	   if(!isRightNumber(_value)) return ;
        	   _selectInput.css({"padding-left":_value+"px"});
        	   
        	   break; 
        	   
           case "label-x"://标签偏移X
        	   
        	   if(!isRightNumber(_value)) return ;
        	   _selectInput.css({"left":_value+"px"});
        	   
        	   break; 
        	   
           case "label-y"://标签偏移Y
        	   
        	   if(!isRightNumber(_value)) return ;
        	   _selectInput.css({"top":_value+"px"});
        	   
        	   break; 
			
           case "labelname-attr"://标签名称
        	   _selectInput.attr("data-value",_value);
	   			_selectInput.find(".value").html(_value);
			  break;
			  
           case "fontsize-attr"://标签字体大小
        	  if(!isRightNumber(_value)) return ;
        	  _selectInput.css({"font-size":_value+"px"});
        	  break;
        	  
           case "height-attr"://标签高度
        	   if(!isRightNumber(_value)) return ;
 		      // height = hMToPx(height);
        	   _selectInput.css({"height":_value+"px","line-height":_value+"px"});
        	   break;
        	   
           case "width-attr"://标签宽度
        	   if(!isRightNumber(_value)) return ;
        	   _selectInput.css({"width":_value+"px"});
        	   break;
        	   
			default:
				break;
			}
			
		})
		
		
		
		//填充值
		function fillValue(width,height,fontsize,value,isvalue,textalign,fontweight,isparent,margin,padding,ishasurl,left,top){
			if(isparent){
			   //模板用毫米单位
				$("#tem-width-px").val(width);
			    $("#tem-height-px").val(height);
				width = pXToHm(width);
				height = pXToHm(height);
				$("#tem-width-attr").val(width);
			    $("#tem-height-attr").val(height);
			}else{
				//标签用像素单元
				$("#width-attr").val(width);
			    $("#height-attr").val(height);
			    $("#fontsize-attr").val(fontsize);
			    $("#labelname-attr").val(value);
			    $("#islabelname-attr").val(isvalue);
			    $("#textalign").val(textalign);
			    $("#fontweight").val(fontweight);
			    $("#ishasurl").val(ishasurl);
			    $("#label-margin").val(margin||_DEFAULT_LABEL_MARGIN);
			    $("#label-padding").val(padding||_DEFAULT_LABEL_PADDING);
			    $("#label-x").val(left||0);
			    $("#label-y").val(top||0);
			}

		}

		//清空值
		function clearValue(){
		    $(".tem-form").find("input,select").val('');
		    $(".tem-form").find("input,select").val('');
		    $(".tem-form").find("#tem-height-px").html('');
		    $(".tem-form").find("#tem-width-px").html('');
			$(".design-area").empty();
			$("#padding").val(_DEFAULT_PADDING);
			$("#label-margin").val(_DEFAULT_LABEL_MARGIN);
			$("#label-padding").val(_DEFAULT_LABEL_PADDING);
			$(".design-area").outerHeight(DEFAULT_TEMPLE_HEIGHT).outerWidth(DEFAULT_TEMPLE_WIDTH);
		}

		//编辑
		function editEle(that){
			var filed = $(that).data("filed");
			
			_____showAttr(filed);
			
		    var width = $(that).outerWidth();
		    var height = $(that).outerHeight();
		    var value = $(that).attr("data-value");
		    var isvalue  =$(that).attr("data-isvalue");
		    var textalign  =$(that).attr("data-textalign");
		    var fontweight  =$(that).attr("data-fontweight");
		    var ishasurl = $(that).data("ishasurl");
		    var fontsize = getFormatValue($(that).css("font-size"));
		    var margin = getFormatValue($(that).css("margin"));
		    var padding = getFormatValue($(that).css("padding-left"));
		    var left = getFormatValue($(that).css("left"));
		    var top = getFormatValue($(that).css("top"));
		    console.log("width:"+width+",height:"+height+",fontsize:"+fontsize+",textalign:"+textalign+",fontweight:"
		    		+fontweight+",margin:"+margin+",padding:"+padding+",ishasurl:"+ishasurl);
		    $(that).addClass("activi-edit-color");
		    fillValue(width,height,fontsize,value,isvalue,textalign,fontweight,false,margin,padding,ishasurl,left,top);
		}

		
		//初始化元素的拖拽和自由放大缩小
		function ____initResizeDrag(isClick){
			$(".design-area").find(".filed-div-item:last").draggable({ 
				containment: ".design-area",
				scroll: false,
				stop: function(event, ui){
					if(event.type != "dragstop"){
						return ;
					}
					editEle(ui.helper);
				}
				});
			$(".design-area").find(".filed-div-item:last").resizable({
				  ghost: true,
				  stop:function(e,obj){
					  if(!isClick)  return ;
					  if(obj.element && typeof obj.element === 'object'){
						  obj.element.click();
					  }
				  }
			});
		}
		
		
		//根据不同的filed显示不同的选项
		function _____showAttr(filed){
			if(filed == "qr_code" || filed == "bar_code"){
				$(".ishasurl").show();
			}else{
				$(".ishasurl").hide();
			}
		}
		
		//显示操作
		$("body").on("click",".filed-div-item",function(e){
			stopPropagation(e);
			$(".filed-opration").hide();
			$(".filed-div-item").removeClass("activi-edit-color");
			$(this).addClass("activi-edit-color");
			$(this).find(".filed-opration").show();
			editEle($(this));
		})
		
		function getFormatValue(fontsize){
			return fontsize.replace("px","");
		}

		//初始化字段列表
		function initFiledList(){
			sys.getApiData("customprint/getFiledList","",function(data){
				console.log("字段列表:%o",data);
				if(data && data.length>0){
					for(var key in data){
						var v = data[key];
						$(".filed-area").append('<div class="filed-li" onclick="temple.clickFiledLi(this)" data-value="'+v.value+'" data-filed="'+v.filed+'"><img src="'+v.img+'"/>'+v.value+'</div>');
					}
				}
			},"GET");
		}

		//点击右侧加字段
		this.clickFiledLi = function (that){
			var filed = $(that).data("filed");
			var value = $(that).data("value");
			var at = $("#defalut-temple").html();
			at = at.replaceAll("%value",value).replaceAll("%filed",filed).replaceAll("%isvalue",1)
			.replaceAll("%textalign",0).replaceAll("%fontweight",0).replaceAll("%ishasurl",0).replaceAll("%left",0).replaceAll("%top",0);
			$(".design-area").append(at);
			
			____initResizeDrag(true);
			
		}

		
		
		
		
		//上传成功之后的方法
		function uploadSuccess(data){
			console.table(data);
			sys.getApiData("customprint/fileList","",function(data){
				console.log("文件列表%o",data);
			},"GET");
		}

		//上传模板
		this.importTemple = function(){
			$("#inputfile").click();
		}

		
		/**
         * 毫米转为px
         */
		function hMToPx(value){
			return numberUtils.FloatMul(value,unit_value);
		}

        /**
         * px转为毫米
         */
		function pXToHm(value){
			return numberUtils.FloatDiv(value,unit_value);
		}
		
		if(isInit){
			this.initPageData();
		}
		
		return that ;
		
	}
	
})(jQuery,window);


//替换所有
String.prototype.replaceAll = function(s1,s2){ 
   return this.replace(new RegExp(s1,"gm"),s2); 
}
